package crossover;

import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import neural.Individual;

public class MultipointCrossover extends AbstractCrossover {
	private List<Integer> points;

	public MultipointCrossover(int[] points) {
		
		Arrays.sort(points);
		for (int i = 0; i < points.length - 1; i++) {
			if (points[i + 1] == points[i]) {
				throw new InvalidParameterException();
			}
		}
		this.points = new ArrayList<Integer>();
		for (int i = 0; i < points.length; i++) {
			this.points.add(points[i]);
		}

		Collections.sort(this.points, new Comparator<Integer>() {
			@Override
			public int compare(Integer o1, Integer o2) {
				return o1 > o2 ? 1 : 0;
			}
		});
	}




	@Override
	protected List<Individual> generateChilds(Individual father2, Individual mother2) {
		List<Double> father = father2.getWeights();
		List<Double> mother = mother2.getWeights();
		
		List<Double> son1 = new ArrayList<Double>();
		List<Double> son2 = new ArrayList<Double>();
		
		int last = 0;
		boolean pair = true;
		for(int i = 0; i <  points.size() ; i++){
			int point = points.get(i);
			if( pair ){
				son1.addAll(father.subList(last, point));
				son2.addAll(mother.subList(last, point));
			}else{
				son1.addAll(mother.subList(last, point));
				son2.addAll(father.subList(last, point));
			}
			pair = !pair;
		
			//son1.addAll(mother.subList(point, next));
		//	son2.addAll(father.subList(point, next));
			last = points.get(i);
		}
		if(pair){
			son1.addAll(father.subList(last, father.size()));
			son2.addAll(mother.subList(last, father.size()));
		}else{
			son1.addAll(mother.subList(last, father.size()));
			son2.addAll(father.subList(last, father.size()));
		}
//		System.out.println("hijo1" + son1);
//		System.out.println("hijo2" + son2);
		List<Individual> resp = new ArrayList<Individual>();
		resp.add(new Individual(son1));
		resp.add(new Individual(son2));
		return resp;
	}
	
}
